#include "clientHead/epoll.h"
#include "clientHead/order_analyse.h"
#include "clientHead/trans_file.h"
#include "clientHead/sys.h"

void handler(int signum){
    printf("Signum = %d\n", signum);
}

int main(int argc, char *argv[])
{
    //./server IP Port username
    ARGS_CHECK(argc, 4);

    signal(SIGPIPE, handler);
    order_train_t* orderTrain = (order_train_t*)calloc(1, sizeof(order_train_t));
    order_train_t* retTrain = (order_train_t*)calloc(1, sizeof(order_train_t));
    
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(atoi(argv[2]));
    servaddr.sin_addr.s_addr = inet_addr(argv[1]);
    
    int ret = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    ERROR_CHECK(ret, -1, "client connect");

    // while(logIn());
    strcpy(orderTrain->train_data, argv[3]);
    orderTrain->data_len = strlen(argv[3]);
    orderTrain->order_len = ORDER_ERROR;
    sendTrain(sockfd, orderTrain);

    int epfd = epoll_create(1);
    epollAdd(epfd, STDIN_FILENO);
    epollAdd(epfd, sockfd);
    struct epoll_event readySet[2];
    char command[] = "请输入您的指令>>  ";
    while(1){
        write(STDOUT_FILENO, command, strlen(command));
        int readyNum = epoll_wait(epfd, readySet, 2, -1);
        for(int i = 0; i < readyNum; ++i){
            if(readySet[i].data.fd == STDIN_FILENO){
                bzero(orderTrain, sizeof(order_train_t));
                read(STDIN_FILENO, orderTrain->train_data, sizeof(orderTrain->train_data));                       
                int ret = order_judg(orderTrain->train_data, orderTrain);
                if(ret  == -1){
                    break;
                }
                printf("train_data:%s\n", orderTrain->train_data);
                sendTrain(sockfd, orderTrain);
            }
            else if(readySet[i].data.fd == sockfd){
                bzero(retTrain, sizeof(order_train_t));
                ret = recvTrain(sockfd, retTrain);
                printf("%s\n", retTrain->train_data);
                int sret = strcmp(retTrain->train_data, "error");
                printf("sret = %d\n",sret);
                if(sret != 0){
                    printf("接收到消息:%s\n", retTrain->train_data);
                }
                // clientExecute();
            }
        }
    }
    close(sockfd);
    return 0;
}


